import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { BriefParam } from './../../model/brief';
import { Component, OnInit } from '@angular/core';
import { Brief } from 'src/app/model/brief';

@Component({
  selector: 'app-brief-adder',
  templateUrl: './brief-adder.component.html',
  styleUrls: ['./brief-adder.component.less']
})
export class BriefAdderComponent implements OnInit {

  phaseTaskId: undefined | number = undefined;
  peroidTaskId: undefined | number = undefined;
  briefForm: FormGroup;
  constructor(
    private fb: FormBuilder,
  ) {
    this.briefForm = fb.group({
      brief: ['', [Validators.required, Validators.maxLength(100)]],
      subject: ['', [Validators.required, Validators.maxLength(10)]],
      phaseTaskId: [],
      periodicTaskId: [],
      id: []
    });
  }

  ngOnInit(): void {
  }

  public setValue(data: Brief): void {
    this.briefForm.setValue({
      brief: data.brief,
      subject: data.subject,
      phaseTaskId: data.phaseTaskId ? data.phaseTaskId : null,
      periodicTaskId: data.periodicTaskId ? data.periodicTaskId : null,
      id: data.id
    });
  }

  public getValue(): BriefParam | null {
    for (const i in this.briefForm.controls) {
      this.briefForm.controls[i].markAsDirty();
      this.briefForm.controls[i].updateValueAndValidity();
    }
    if (this.briefForm.valid) {
      const resutl: BriefParam = this.briefForm.value;
      resutl.phaseTaskId = this.phaseTaskId;
      resutl.periodicTaskId = this.peroidTaskId;
      return resutl;
    }
    return null;
  }

  public reset(): void {
    this.briefForm.reset();
    this.peroidTaskId = undefined;
    this.phaseTaskId = undefined;
  }

  public setPhaseTaskId(taskId: number): void {
    this.phaseTaskId = taskId;
  }

  public setPeroidTaskId(taskId: number): void {
    this.peroidTaskId = taskId;
  }

}
